/**
 * 
 */
package com.user_hosted_storage.server.dal;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

/**
 * @author helios
 *
 */
public abstract class GenericFacade<T> {

	@PersistenceContext
	protected EntityManager em;
	
	public void create(T t){
		em.persist(t);
	}
	
	public void edit(T t){
    	em.merge(t);
    }

	public void remove(T t){
    	em.remove(em.merge(t));
    }
	

	public T find(Object id) {
		@SuppressWarnings("unchecked")
		Class<T> entityBeanType = ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
		return find(entityBeanType,id);
	}
	
	public String getEntityName() {
		@SuppressWarnings("unchecked")
		Class<T> entityBeanType = ((Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]);
		return entityBeanType.getSimpleName();
	}	

	public T find(Class<T> clazz, Object id){
		return em.find(clazz, id);
	}

	@SuppressWarnings("unchecked")
	public List<T> findAll(){
		return em.createQuery("select m from "+getEntityName()+" m").getResultList();
	}
	
	public void removeAll(){
		Query query = em.createQuery("delete from "+getEntityName()+" m");
		query.executeUpdate();
	}
}
